import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<WebState> buildEffect() {
  return combineEffects(<Object, Effect<WebState>>{
    WebAction.onDone: _onDone,
    WebAction.onShare: _onShare,
  });
}

void _onDone(Action action, Context<WebState> ctx) {
  Navigator.of(ctx.context).pop(ctx.state.done);
}

void _onShare(Action action, Context<WebState> ctx) async {
  var url = ctx.state.url;
  var title = ctx.state.title;
  var desc = "AI老师给你作文意想不到的精批细改！";
  var image = "assets://assets/images/ic_launcher.png";

  if (url.startsWith(
          GlobalState.baseUrl("/correct/pub/view/machine/review.mvc?id=")) &&
      url.endsWith("&ishomework=1")) {
    String imageUrl = GlobalState.baseUrl(
            "/correct/pub/anyone/view/share/machine/review.mvc?shwId=") +
        url.substring(url.indexOf("id=") + 3).replaceAll("&ishomework=1", "");
    Navigator.of(ctx.context)
        .pushReplacementNamed(Nav.WEB_SHARE_PAGE, arguments: {'url': imageUrl});
    return;
  }

  final String select = await Util.showShareDialog(ctx.context);

  if (url.contains('?')) {
    url += "&ticket=wxShare";
  }
  if (select == 'session') {
    fluwx.share(fluwx.WeChatShareWebPageModel(
        title: title,
        description: desc,
        scene: fluwx.WeChatScene.SESSION,
        webPage: url,
        thumbnail: image));
  } else if (select == 'timeline') {
    fluwx.share(fluwx.WeChatShareWebPageModel(
        title: title,
        description: desc,
        scene: fluwx.WeChatScene.TIMELINE,
        webPage: url,
        thumbnail: image));
  }
}

//Timer _timer;
//var _counter = 0;
//
//void _startCountupTimer(Context<WebState> ctx, max) {
//  const oneSec = const Duration(seconds: 1);
//
//  var callback = (timer) {
//    if (ctx.isDisposed) {
//      _timer.cancel();
//      return;
//    }
//
//    ctx.dispatch(WebActionCreator.countUp(_counter));
//    if (_counter == max) {
//      _timer.cancel();
//    } else {
//      _counter += 1;
//    }
//  };
//
//  _counter = 1;
//  ctx.dispatch(WebActionCreator.countUp(_counter));
//  _counter += 1;
//
//  _timer = Timer.periodic(oneSec, callback);
//}

//void _cancelTimer(Context<WebState> ctx) {
//  _timer.cancel();
//  _counter = 0;
//  ctx.dispatch(WebActionCreator.onCountUp(0));
//}
